import FormUtil from '@/framework/infra/form/FormUtil'
import NameUtil from '@/framework/infra/name/NameUtil'
import ValueUtils from '@/framework/infra/value/ValueUtils'
import TableSetting from '@/framework/components/table/TableSetting'

export default class BaseTableService {
  constructor(table) {
    this.table = table
  }

  get baseRequestApi() {
    return this.table.option.requestApi
  }

  get buttons() {
    return this.table.buttons
  }

  isButtonShowed(row, button) {
    if (button.showFilter) {
      return button.showFilter(row)
    }
    if (button.funcType === 'online') {
      return row.status === 0
    } else if (button.funcType === 'offline') {
      return row.status === 1
    }
    return true
  }

  // 派发
  dispatch({ funcType, label = '' }, args = null) {
    funcType = this.getFuncTypeHandler(funcType)
    if (!this[funcType]) {
      console.error(funcType + '的事件没有实现')
      return
    }
    return this[funcType](args, label)
  }

  resetForm() {
    // this.table.tableOption.columns.filter(el => el.formCached)
    FormUtil.reset(this.table.formData, Object.assign(
      this.table.initFormData,
      TableSetting.getDefaultLocalSearchParam(),
      TableSetting.getDefaultLocalFormCachedParam()
    ))
  }

  getFuncTypeHandler(funcType) {
    return NameUtil.camelCase('handle', funcType)
  }

  hasFuncType(funcType) {
    return this.getFuncTypeHandler(funcType) in this
  }

  reloadTable() {
    this.table.reloadTable()
  }

  get selectedItems() {
    return this.table.getMultipleSelection() || []
  }

  get notEmptySelectedItems() {
    const result = this.selectedItems
    if (!result.length) {
      this.error('请选择至少一条记录')
      return null
    }
    return result
  }

  get selectedIds() {
    return this.selectedItems.map(el => el.id)
  }

  get notEmptySelectedIds() {
    const selectedItems = this.notEmptySelectedItems
    if (selectedItems) {
      return selectedItems.map(el => el.id)
    }
    return selectedItems
  }

  get hasSelectOne() {
    return this.selectedItems.length > 0
  }

  success(msg = '删除成功') {
    this.table.$success(msg)
  }

  hideFormDialog() {
    this.table.hideFormDialog()
  }

  error(msg) {
    this.table.$error(msg)
  }

  confirm(msg, title = '提示') {
    return this.table.$confirm(msg, title)
  }

  handleCreate() {
    this.table.setInEdit(false)
    this.resetForm()
    this.table.clearValidate()
    if (this.table.tableOption?.interceptor?.beforeCreate) {
      this.table.tableOption?.interceptor?.beforeCreate(this.table.formData)
    }
    this.table.showFormDialog()
  }

  handleSetSortNum(row) {
    this.table.showSetSortNumDialog(row)
  }

  handleView(row) {
    // this.table.setInEdit(false)
    if (this.table.tableOption.loadDetail) {
      this.table.dialogLoading = true
      this.baseRequestApi.detail(row.id).then(data => {
        FormUtil.fill(this.table.formData, data)
        // if (this.table.tableOption?.interceptor?.beforeEdit) {
        //   this.table.tableOption?.interceptor?.beforeEdit(this.table.formData)
        // }
      }).finally(() => {
        this.table.dialogLoading = false
      })
    } else {
      FormUtil.fill(this.table.formData, row)
      // if (this.table.tableOption?.interceptor?.beforeEdit) {
      //   this.table.tableOption?.interceptor?.beforeEdit(this.table.formData)
      // }
    }
    // this.table.showFormDialog()
    this.table.showViewDialog()
  }

  handleUpdate(row) {
    this.table.setInEdit(true)
    if (this.table.tableOption.loadDetail) {
      this.table.dialogLoading = true
      this.baseRequestApi.detail(row.id).then(data => {
        FormUtil.fill(this.table.formData, data)
        if (this.table.tableOption?.interceptor?.beforeEdit) {
          this.table.tableOption?.interceptor?.beforeEdit(this.table.formData)
        }
      }).finally(() => {
        this.table.dialogLoading = false
      })
    } else {
      FormUtil.fill(this.table.formData, row)
      // console.log(this.table.formData)
      if (this.table.tableOption?.interceptor?.beforeEdit) {
        this.table.tableOption?.interceptor?.beforeEdit(this.table.formData)
      }
    }
    this.table.showFormDialog()
  }

  handleCopy(row) {
    this.table.setInEdit(false)
    if (this.table.tableOption.loadDetail) {
      this.table.dialogLoading = true
      this.baseRequestApi.detail(row.id).then(data => {
        FormUtil.fill(this.table.formData, data)
        if (this.table.tableOption?.interceptor?.beforeCopy) {
          this.table.tableOption?.interceptor?.beforeCopy(this.table.formData)
        }
        // console.log(this.table.formData)
      }).finally(() => {
        this.table.dialogLoading = false
      })
    } else {
      FormUtil.fill(this.table.formData, row)
      // console.log(this.table.formData)
      if (this.table.tableOption?.interceptor?.beforeCopy) {
        this.table.tableOption?.interceptor?.beforeCopy(this.table.formData)
      }
    }
    this.table.showFormDialog()
  }

  async handleRemove(row) {
    await this.table.$confirm('确认删除吗？', '提示')
    await this.baseRequestApi.remove(row.id)
    this.success('删除成功')
    this.reloadTable()
  }
  

  async handleBatchRemove() {
    if (!this.hasSelectOne) {
      this.error('请选择至少一条记录')
      return
    }
    await this.confirm('确认删除所选记录吗？', '提示')
    await this.baseRequestApi.removeMany(this.selectedIds)
    this.success('删除成功')
    this.reloadTable()
  }

  async handleSubmitFormAndContinue(args) {
    return this.handleSubmitForm(args, () => {
      this.resetForm()
      this.table.clearValidate()
      if (this.table.tableOption?.interceptor?.beforeCreate) {
        this.table.tableOption?.interceptor?.beforeCreate(this.table.formData)
      }
    })
  }

  async handleSubmitForm(args, callback = null) {
    try {
      let updateApiName = ''
      if (this.table.isEdit) {
        updateApiName = this.table.tableOption?.requestApiNames?.update || 'update'
      } else {
        updateApiName = this.table.tableOption?.requestApiNames?.create || 'create'
      }
      const postParam = { ...args, ...ValueUtils.getValue(this.table.option.initFormParams) }
      console.log(postParam)
      const result = await this.baseRequestApi[updateApiName](postParam)
      if (args.id) {
        this.table.emitEvent('editSuccess', result)
        this.success('修改成功')
      } else {
        if (!this.table.emitEvent('addSuccess', result)) {
          this.success('添加成功')
        }
      }
      const propList = this.table.tableOption.columns.filter(el => el.formCached).map(el => el.prop)
      if (propList.length > 0) {
        TableSetting.saveDefaultLocalFormCachedParam(propList.reduce((r, a) => {
          r[a] = postParam[a]
          return r
        }, {}))
      }
      // TableSetting.getDefaultLocalFormCachedParam()
      this.reloadTable()
      if (callback) {
        callback()
      } else {
        this.hideFormDialog()
      }
    } catch (e) {
      if (e.code === 501) {
        this.table.$confirm(e.msg, '确认').then(() => {
          args._confirm = true
          this.table.tableOption?.beforeConfirmSubmit(e.msg, args)
          this.handleSubmitForm(args)
        })
        return
      }
      if (!e.message) {
        return
      }
      this.error(e.message)
    }
  }

  async handleSubmitSetSortNum(args) {
    await this.baseRequestApi.setSortNum(args)
    this.success('修改成功')
    this.reloadTable()
    this.table.hideSetSortNumDialog()
  }

  async handleBatchOffline() {
    if (!this.hasSelectOne) {
      this.error('请选择至少一条记录')
      return
    }
    await this.confirm('确认批量下线吗？')
    await this.baseRequestApi.batchOffline(this.selectedIds)
    this.success('批量下线成功')
    this.reloadTable()
  }

  async handleSetAsTop(row) {
    await this.confirm(`确认置顶吗？`)
    await this.baseRequestApi.setAsTop(row.id)
    this.success(`置顶成功`)
    this.reloadTable()
  }

  async handleBatchOnline() {
    if (!this.hasSelectOne) {
      this.error('请选择至少一条记录')
      return
    }
    await this.confirm('确认批量上线吗？')
    await this.baseRequestApi.batchOnline(this.selectedIds)
    this.success('批量上线成功')
    this.reloadTable()
  }

  async handleOffline(row, label) {
    await this.confirm(`确认${label}吗？`)
    await this.baseRequestApi.offline(row.id)
    this.success(`${label}成功`)
    // eslint-disable-next-line require-atomic-updates
    // row.status = 0
    this.reloadTable()
  }

  async handleOnline(row, label) {
    await this.confirm(`确认${label}吗？`)
    await this.baseRequestApi.online(row.id)
    this.success(`${label}成功`)
    // eslint-disable-next-line require-atomic-updates
    // row.status = 1
    this.reloadTable()
  }

  async handleSetShowFlag(row) {
    await this.confirm('确认设置前端显示吗')
    await this.baseRequestApi.modifyShowFlag(1, [row.id])
    this.success('设置成功')
    // eslint-disable-next-line require-atomic-updates
    row.showFlag = 1
  }

  async handleCancelShowFlag(row) {
    await this.confirm('确认取消前端显示吗')
    await this.baseRequestApi.modifyShowFlag(0, [row.id])
    this.success('取消成功')
    // eslint-disable-next-line require-atomic-updates
    row.showFlag = 0
  }

  async handleBatchSetShowFlag() {
    const ids = this.notEmptySelectedIds
    if (ids) {
      await this.confirm('确认设置所选前端显示吗')
      await this.baseRequestApi.modifyShowFlag(1, ids)
      this.reloadTable()
      this.success('设置成功')
    }
  }

  async handleBatchCancelShowFlag() {
    const ids = this.notEmptySelectedIds
    if (ids) {
      await this.confirm('确认取消所选前端显示吗')
      await this.baseRequestApi.modifyShowFlag(0, ids)
      this.reloadTable()
      this.success('取消成功')
    }
  }

  async handleCheckReject(row) {
    const { value } = await this.table.$prompt('确认审核拒绝所选记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S/,
      inputErrorMessage: '处理意见不能为空'
    })
    await this.baseRequestApi.check({ checkStatus: 10, checkRemark: value || '', idList: [row.id] })
    this.reloadTable()
    this.success('拒绝成功')
  }
  async handleAuditReject(row) {
    await this.confirm('确认拒绝通过吗')
    await this.baseRequestApi.check({ commentId: row.id, audit: 2 })
    this.reloadTable()
    this.success('拒绝成功')
  }
  async handleCheckResolve(row) {
    await this.confirm('确认审核通过吗')
    await this.baseRequestApi.check({ checkStatus: 5, checkRemark: '', idList: [row.id] })
    this.reloadTable()
    this.success('通过成功')
  }

  async handleBatchCheckResolve() {
    const ids = this.notEmptySelectedIds
    if (ids) {
      await this.confirm('确认审核通过所选记录吗')
      await this.baseRequestApi.check({ checkStatus: 5, checkRemark: '', idList: ids })
      this.reloadTable()
      this.success('通过成功')
    }
  }
  async handleAuditResolve(row) {
    await this.confirm('确认审核通过吗')
    await this.baseRequestApi.check({ commentId: row.id, audit: 1 })
    this.reloadTable()
    this.success('通过成功')
  }


  async handleBatchCheckReject() {
    const ids = this.notEmptySelectedIds
    if (ids) {
      const { value } = await this.table.$prompt('确认审核拒绝所选记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '处理意见不能为空'
      })
      await this.baseRequestApi.check({ checkStatus: 10, checkRemark: value || '', idList: ids })
      this.reloadTable()
      this.success('拒绝成功')
    }
  }
}
